/*
'  DotNetNuke -  http://www.dotnetnuke.com
'  Copyright (c) 2002-2011
'  by DotNetNuke Corporation
' 
'  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
'  documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
'  the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
'  to permit persons to whom the Software is furnished to do so, subject to the following conditions:
' 
'  The above copyright notice and this permission notice shall be included in all copies or substantial portions 
'  of the Software.
' 
'  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
'  TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
'  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
'  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
'  DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using DotNetNuke.Common.Lists;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Framework;
using DotNetNuke.Modules.Store.Providers;
using DotNetNuke.Modules.Store.Providers.Address;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.UserControls;
using DotNetNuke.UI.WebControls;

namespace DotNetNuke.Modules.Store.Providers.Address.DefaultAddressProvider
{
	/// <summary>
	///		Summary description for StoreAddress.
	/// </summary>
	public partial class StoreAddress : UserControlBase
	{
        #region Private Declarations

		private int startTabIndex = 1;
		private bool enabled = true;
		private IAddressInfo addressInfo = null;
        private bool showUserSaved = false;
        private bool showPrimary = false;
        private bool showDescription = false;
        private bool showFirstName = true;
        private bool showLastName = true;
		private bool showStreet = true; 
		private bool showUnit = true; 
		private bool showPostal = true; 
		private bool showCity = true; 
		private bool showCountry = true; 
		private bool showRegion = true; 
		private bool showEmail = true; 
		private bool showTelephone = true; 
		private bool showCell = true; 
		private string countryData = "Text"; 
		private string regionData = "Text";
		private string MyFileName = "StoreAddress.ascx";

        #endregion

        #region Public Functions/Properties

        public string LocalResourceFile
        {
            get { return Localization.GetResourceFile(this, MyFileName); }
        }
		
		public bool Enabled
		{
			get { return enabled; }
			set 
			{
				enabled = value;
				foreach (WebControl control in GetInputControls())
                    control.Enabled = enabled;
            }
		}
		
		public IAddressInfo AddressInfo
		{
			get 
			{
                if (addressInfo != null && HasChanged == true)
                {
                    // Used for secure fields content
                    PortalSecurity security = new PortalSecurity();
                    //-1 indicates that this is a new address and not one selected from the drop down list.
                    addressInfo.AddressID = int.Parse(this.hiddenAddressId.Value.Length > 0 ? this.hiddenAddressId.Value : Null.NullInteger.ToString());
                    addressInfo.Description = security.InputFilter(this.txtDescription.Text, PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.FirstName = security.InputFilter(this.txtFirstName.Text, PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.LastName = security.InputFilter(this.txtLastName.Text, PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.Address1 = security.InputFilter(this.txtStreet.Text, PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.Address2 = security.InputFilter(this.txtUnit.Text, PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.PostalCode = security.InputFilter(this.txtPostal.Text, PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.City = security.InputFilter(this.txtCity.Text, PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.CountryCode = security.InputFilter(GetSelectedCountry(), PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.RegionCode = security.InputFilter(GetSelectedRegion(), PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.Email = security.InputFilter(this.txtEmail.Text, PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.Phone1 = security.InputFilter(this.txtTelephone.Text, PortalSecurity.FilterFlag.NoMarkup);
                    addressInfo.Phone2 = security.InputFilter(this.txtCell.Text, PortalSecurity.FilterFlag.NoMarkup);
                    if (rowPrimary.Visible == true)
                        addressInfo.PrimaryAddress = chkPrimary.Checked;
                    else
                        addressInfo.PrimaryAddress = bool.Parse(this.hiddenPrimaryAddress.Value.Length > 0 ? this.hiddenPrimaryAddress.Value : "false");
                    addressInfo.UserSaved = chkUserSaved.Checked;
                    addressInfo.Modified = true;
                }
				return addressInfo; 
			}
            set { addressInfo = value; }
		}

		public int StartTabIndex 
		{
            set { startTabIndex = value; } 
		} 

		public bool ShowUserSaved
		{
            set { showUserSaved = value; } 
		}

        public bool ShowPrimary
		{
            set { showPrimary = value; } 
		}

        public bool ShowDescription
        {
            set { showDescription = value; }
        } 

		public bool ShowFirstName
		{
            set { showFirstName = value; } 
		} 

		public bool ShowLastName
		{
            set { showLastName = value; } 
		} 

		public bool ShowStreet 
		{
            set { showStreet = value; } 
		} 

		public bool ShowUnit 
		{
            set { showUnit = value; } 
		} 

		public bool ShowPostal 
		{
            set { showPostal = value; } 
		} 

		public bool ShowCity 
		{
            set { showCity = value; } 
		} 

		public bool ShowCountry 
		{
            set { showCountry = value; } 
		} 

		public bool ShowRegion 
		{
            set { showRegion = value; } 
		} 

		public bool ShowEmail 
		{
            set { showEmail = value; } 
		} 

		public bool ShowTelephone 
		{
            set { showTelephone = value; } 
		} 

		public bool ShowCell 
		{
            set { showCell = value; } 
		}

		public string CountryData 
		{
            set { countryData = value; } 
		} 

		public string RegionData 
		{
            set { regionData = value; } 
		}

        public bool HasChanged
        {
            get
            {
                object hasChanged = ViewState["HasChanged"];
                if (hasChanged == null)
                    return false;
                else
                    return (bool)hasChanged;
            }
            set { ViewState["HasChanged"] = value; }
        }

        #endregion

        #region Public Methods

        public void PopulateAddress()
		{
            if (addressInfo != null) 
			{
				hiddenAddressId.Value = addressInfo.AddressID.ToString();
                chkUserSaved.Checked = addressInfo.UserSaved;
                chkPrimary.Checked = addressInfo.PrimaryAddress;
                hiddenPrimaryAddress.Value = addressInfo.PrimaryAddress.ToString();
                txtDescription.Text = addressInfo.Description;
				txtFirstName.Text = addressInfo.FirstName;
				txtLastName.Text = addressInfo.LastName;
				txtStreet.Text = addressInfo.Address1;
				txtUnit.Text = addressInfo.Address2;
				txtPostal.Text = addressInfo.PostalCode;
				txtCity.Text = addressInfo.City;
				txtEmail.Text = addressInfo.Email;
				txtTelephone.Text = addressInfo.Phone1;
				txtCell.Text = addressInfo.Phone2;

                cboCountry.ClearSelection();
                if (string.IsNullOrEmpty(addressInfo.CountryCode) == true)
                    cboCountry.SelectedIndex = 0;
                else
                {
                    ListItem country = null;
                    if (countryData.ToLower() == "text")
                        country = cboCountry.Items.FindByText(addressInfo.CountryCode);
                    else if (countryData.ToLower() == "value")
                        country = cboCountry.Items.FindByValue(addressInfo.CountryCode);
                    if (country != null)
                        country.Selected = true;
                }

                Localize();

                if (cboRegion.Items.Count > 0)
                {
                    cboRegion.ClearSelection();
                    if (string.IsNullOrEmpty(addressInfo.RegionCode) == true)
                        cboRegion.SelectedIndex = 0;
                    else
                    {
                        ListItem region = null;
                        if (regionData.ToLower() == "text")
                            region = cboRegion.Items.FindByText(addressInfo.RegionCode);
                        else if (regionData.ToLower() == "value")
                            region = cboRegion.Items.FindByValue(addressInfo.RegionCode);
                        if (region != null)
                            region.Selected = true;
                    }
                }
                else
                    txtRegion.Text = addressInfo.RegionCode; 
			}
            else
                Localize();
            HasChanged = false;
            ShowRequiredFields();
        }

        #endregion

        #region Web Form Designer generated code

        override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            loadCountryList();
        }

		#endregion

        #region Event Handlers

        protected void Page_Load(object sender, System.EventArgs e)
		{
            if (IsPostBack == false)
            {
                short tabIndex = (short)startTabIndex;
                foreach (WebControl control in GetInputControls())
                    control.TabIndex = tabIndex++;
            }
		}

        protected void address_TextChanged(object sender, EventArgs e)
        {
            HasChanged = true;
        }

        protected void cboCountry_SelectedIndexChanged(object sender, System.EventArgs e)
		{
            HasChanged = true;
            Localize();
		}

        protected void cboRegion_SelectedIndexChanged(object sender, System.EventArgs e)
		{
            HasChanged = true;
        }

        protected void chkUserSaved_CheckedChanged(object sender, EventArgs e)
        {
            rowPrimary.Visible = chkUserSaved.Checked;
            rowDescription.Visible = chkUserSaved.Checked;
            HasChanged = true;
        }

        protected void chkPrimary_CheckedChanged(object sender, EventArgs e)
        {
            HasChanged = true;
        }

        #endregion

        #region Private Functions

        private List<WebControl> GetInputControls() 
		{
            string cacheKey = "StoreAddressInputControls_P" + PortalSettings.PortalId.ToString();
            List<WebControl> inputControls = (List<WebControl>)DataCache.GetCache(cacheKey);

            if (inputControls == null)
            {
                inputControls = new List<WebControl>(15);
                inputControls.Add(chkUserSaved);
                inputControls.Add(chkPrimary);
                inputControls.Add(txtDescription);
                inputControls.Add(txtFirstName);
                inputControls.Add(txtLastName);
                inputControls.Add(txtStreet);
                inputControls.Add(txtUnit);
                inputControls.Add(txtPostal);
                inputControls.Add(txtCity);
                inputControls.Add(cboCountry);
                inputControls.Add(cboRegion);
                inputControls.Add(txtRegion);
                inputControls.Add(txtEmail);
                inputControls.Add(txtTelephone);
                inputControls.Add(txtCell);
                DataCache.SetCache(cacheKey, inputControls);
            }

            return inputControls;
		}

		private string GetSelectedCountry() 
		{
            string retvalue = "";

            if (cboCountry.SelectedIndex > 0)
            {
                if (countryData.ToLower() == "text")
                    retvalue = cboCountry.SelectedItem.Text;
                else if (countryData.ToLower() == "value")
                    retvalue = cboCountry.SelectedItem.Value;
            }

            return retvalue; 
		}

		private string GetSelectedRegion()
		{ 
			string retvalue = "";

            if (cboRegion.SelectedIndex > 0)
            {
               if (regionData.ToLower() == "text")
                    retvalue = cboRegion.SelectedItem.Text;
                else if (regionData.ToLower() == "value")
                    retvalue = cboRegion.SelectedItem.Value;
            } 
			else 
				retvalue = txtRegion.Text; 

			return retvalue; 
		} 

		private void Localize() 
		{ 
			string countryCode = cboCountry.SelectedItem.Value;
            cboRegion.Items.Clear();

            if (string.IsNullOrEmpty(countryCode) == false)
            {
                ListController ctlEntry = new ListController();
                string listKey = "Country." + countryCode;
                ListEntryInfoCollection entryCollection = ctlEntry.GetListEntryInfoCollection("Region", listKey);

                if (entryCollection.Count != 0)
                {
                    cboRegion.DataSource = entryCollection;
                    cboRegion.DataBind();
                    cboRegion.Items.Insert(0, new ListItem("< " + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + " >", ""));

                    if (countryCode.ToLower() == "us")
                    {
                        plPostal.Text = Services.Localization.Localization.GetString("Zip", LocalResourceFile);
                        plPostal.HelpText = Services.Localization.Localization.GetString("Zip.Help", LocalResourceFile);
                        plRegion.Text = Services.Localization.Localization.GetString("State", LocalResourceFile);
                        plRegion.HelpText = Services.Localization.Localization.GetString("State.Help", LocalResourceFile);
                        valRegion1.ErrorMessage = Services.Localization.Localization.GetString("StateRequired", Services.Localization.Localization.GetResourceFile(this, MyFileName));
                    }
                    else
                    {
                        plPostal.Text = Services.Localization.Localization.GetString("plPostal", LocalResourceFile);
                        plPostal.HelpText = Services.Localization.Localization.GetString("plPostal.Help", LocalResourceFile);
                        plRegion.Text = Services.Localization.Localization.GetString("Province", LocalResourceFile);
                        plRegion.HelpText = Services.Localization.Localization.GetString("Province.Help", LocalResourceFile);
                        valRegion1.ErrorMessage = Services.Localization.Localization.GetString("ProvinceRequired", LocalResourceFile);
                    }

                    cboRegion.Visible = true;
                    plRegion.ControlName = "cboRegion";
                    txtRegion.Visible = false;
                    valRegion1.Enabled = true;
                    valRegion2.Enabled = false;
                    return;
                }
            }

            cboRegion.ClearSelection(); 
			cboRegion.Visible = false; 
			txtRegion.Visible = true;
            plRegion.ControlName = "txtRegion";
			valRegion1.Enabled = false; 
			valRegion2.Enabled = true;
            plPostal.Text = Services.Localization.Localization.GetString("plPostal", LocalResourceFile);
            plPostal.HelpText = Services.Localization.Localization.GetString("plPostal.Help", LocalResourceFile);
            plRegion.Text = Services.Localization.Localization.GetString("plRegion", LocalResourceFile);
            plRegion.HelpText = Services.Localization.Localization.GetString("plRegion.Help", LocalResourceFile);
            valRegion2.ErrorMessage = Services.Localization.Localization.GetString("RegionRequired", LocalResourceFile);
		} 

		private void loadCountryList() 
		{
			ListController ctlEntry = new ListController(); 
			ListEntryInfoCollection entryCollection = ctlEntry.GetListEntryInfoCollection("Country"); 
			cboCountry.DataSource = entryCollection; 
			cboCountry.DataBind();
            cboCountry.Items.Insert(0, new ListItem("< " + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + " >", "")); 
            cboCountry.SelectedIndex = 0;
        }

        private void ShowRequiredFields()
        {
            rowUserSaved.Visible = showUserSaved;
            rowPrimary.Visible = showPrimary;
            rowDescription.Visible = showDescription;
            rowFirstName.Visible = showFirstName;
            rowLastName.Visible = showLastName;
            rowStreet.Visible = showStreet;
            rowUnit.Visible = showUnit;
            rowPostal.Visible = showPostal;
            rowCity.Visible = showCity;
            rowRegion.Visible = showRegion;
            rowCountry.Visible = showCountry;
            rowEmail.Visible = showEmail;
            rowTelephone.Visible = showTelephone;
            rowCell.Visible = showCell;
        }

        #endregion
    }
}
